<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/3
 * Time: 10:53
 */

namespace app\applet\model;


use think\Db;
use think\Exception;
use Stbz\Api\SupplyClient;
use think\Config;
class Cart
{

    private $appKey   = 'A855F0BA1EBCD119BEFBDE6EC07ECE65';
    private $appSecret = '68B892679EB78F9FB45ED3D62DE838B7';

    public function __construct()
    {
        vendor("JuHe.autoload");


    }
    /**
     * 添加购物车
     */
    public function addCart($data)
    {
        $tm=time();
        if(in_array($data['source_type'],[2,3])){
            //库存判断
            //判断商品状态
            $goodsInfo=Db::name("choice_goods")->where(['goods_id'=>$data['goods_id']])->find();
            $status=$goodsInfo['status'];
            $supply_delete_status=$goodsInfo['supply_delete_status'];
            $shop_status =$goodsInfo['shop_status'];
            $shop_delete_status =$goodsInfo['shop_delete_status'];

            if(empty($status)||$shop_status==2){
                returnJson(-2003,'商品已下架');
            }
            if(empty($supply_delete_status)||empty($shop_delete_status)){
                returnJson(-2003,'商品已删除');
            }
            //获取当前规格价格
            $method = 'GET';//请求方法
            $action = '/v2/Goods/Detail';//请求资源名

            $this->client = new SupplyClient( $this->appKey, $this->appSecret);
            $response = $this->client->getApiResponse($method,$action,['id'=> $data['goods_id']]);
            $response = json_decode($response,true);
            if($response['code'] !== 1)
            {
                returnJson(-2004,"商品ID异常");
            }
            $response = $response["data"];

            $optionsList=$response["specs"]['options'];

            $isExt=false;
            foreach ( $optionsList as $option){
                if($option['id']==$data['spec_id']){
                    $spec=$option;
                    $isExt=true;
                }
            }

            if(empty($isExt)){
                returnJson(-2003,'商品【'.$goodsInfo['title']."】该规格不存在");
            }

            $stock=$spec['stock'];
            if($data["goods_num"]>$stock){
                returnJson(-2003,'商品【'.$goodsInfo['title']."】库存不足");
            }
            #处理价格数据
            $inserData=[];
            $computePrice=$this->computePrice($data['goods_id'],$data['source_type'],$spec['agreement_price']);
            if($data['source_type']==2){//返利商城
                $price=$computePrice['price'];
                $gold_coin=0;
                $rebate_score=  $computePrice['activity_buyer'];
                $rebate_coin = 0;
                $inserData['rebate_coin']=$rebate_coin;
                $inserData['rebate_score']=$rebate_score;
            }elseif($data['source_type']==3){//爆品商城
                $price = $computePrice['price'];
                $gold_coin = $computePrice['gold_coin'];
            }

            $inserData['goods_id']=$data['goods_id'];
            $inserData['spec_name']=$spec['spec_value_names'];
            $inserData['score_amount']=$price;
            $inserData['coin_amount']=$gold_coin;
            $inserData['goods_num']=$data['goods_num'];
            $inserData['spec_id']=$data['spec_id'];
            $inserData['source_type']=$data['source_type'];
            $inserData['store_id']=0;//商家ID  取来源类型
            $inserData['member_id']=$data['member_id'];
            $inserData['create_time']=$tm;
            $inserData['update_time']=$tm;
            $cart_id=Db::name('cart')->insertGetId($inserData);
            if($cart_id<=0){
                returnJson(-2004,'添加失败');
            }
            return  $cart_id;
        }else{
            //获取商品主要信息
            $goods=Db::name("goods")->where(['goods_id'=>$data["goods_id"]])
                ->field("g_type,member_id,goods_id,store_id,source_type,is_delete,limit_number,
                limit_start_time,limit_end_time,limit_num_status,limit_time_status,status")
                ->find();

            if(empty($goods['goods_id'])||$goods['is_delete']==2){
                returnJson(-2003,'当前商品不存在或已删除');
            }
            if($goods['status']!=1){
                returnJson(-2003,'当前商品未上架');
            }
            if(empty($data['goods_num'])){//新增商品数量
                $data['goods_num']=1;
            }

            //判断是否为商家自己的商品
            if($goods['member_id']==$data["member_id"]){
                returnJson(-2003,'当前商品为当前用户商家商品');
            }
            //判断是否选中配送方式
            $goodsInfo=Db::name("goods_info")
                ->where(['goods_id'=>$data["goods_id"]])
                ->field("distribution_method,delivery_type,delivery_fee")
                ->find();
            $distribution_method=$goodsInfo['distribution_method'];
            $d_method=0;
            if($distribution_method>0){
                $d_method=$data['d_method'];
                if(empty($d_method)){
                    returnJson(-2003,'请选中配送方式');
                }
                if(!in_array($d_method,array(1,2))){
                    returnJson(-2003,'参数不合法');
                }
            }
            //判断商品是否限购
            if($goods['limit_num_status']==2){//限购
                $limit_number=$goods['limit_number'];
                //规格ID
                $buyNums=Db::name("order_goods")->alias("og")
                    ->join("mm_order o","og.order_id=o.order_id")
                    ->where(['o.pay_status'=>2,"og.goods_id"=>$data["goods_id"],"o.member_id"=>$data["member_id"]])
                    ->value("og.goods_num");
                if($buyNums>=$limit_number){
                    returnJson(-2003,"当前商品限购".$limit_number);
                }
            }
            //判断活动是否限时
            if($goods['limit_time_status']==2){//限时
                if($tm<$goods['limit_start_time']){
                    returnJson(-2003,'当前商品活动还未开始');
                }

                if($tm>$goods['limit_end_time']){
                    returnJson(-2003,'当前商品活动已经过期');
                }

            }
            //获取商品规格及相关信息
            $goods_spec_nums=Db::name("goods_spec")
                ->where(['goods_id'=>$data['goods_id'],'gs_id'=>$data['spec_id']])
                ->value("num");

            if($goods_spec_nums<$data['goods_num']&&!in_array($goods['g_type'],[4,5])){
                returnJson(-2003,'当前规格商品库存不足');
            }
            $count = Db::name("cart")
                ->where(['member_id'=>$data["member_id"],'goods_id'=>$data["goods_id"],'spec_id'=>$data["spec_id"],"d_method"=>$d_method])
                ->count();

            if($count)
            {
                $cart_id  = Db::name("cart")
                    ->where(['member_id'=>$data["member_id"],'goods_id'=>$data["goods_id"],'spec_id'=>$data["spec_id"],"d_method"=>$d_method])
                    ->setInc("goods_num",$data["goods_num"]);
                if($cart_id){
                    return   $cart_id;
                }else{
                    returnJson(-2004,'新增购物车失败');
                }
            }else{
                Db::startTrans();
                try{
                    if($d_method>0){
                        $nums = Db::name("cart")
                            ->where(['member_id'=>$data["member_id"],'goods_id'=>$data["goods_id"],'spec_id'=>$data["spec_id"]])
                            ->count();
                        if($nums){
                            Db::name("cart")
                                ->where(['member_id'=>$data["member_id"],'goods_id'=>$data["goods_id"],'spec_id'=>$data["spec_id"]])
                                ->delete();
                        }
                    }

                    if($d_method==1){//送货上门
                        $data['d_method']=$d_method;

                        if($goodsInfo['delivery_type']==1){//自己配送
                            $data['d_type']=1;
                            $data['d_fee']=$goodsInfo['delivery_fee'];

                        }elseif($goodsInfo['delivery_type']==2){//第三方配送
                            $data['d_type']=2;
                            //获取第三方计算金额
                        }
                    }elseif($d_method==2){//到店消费
                        $data['d_method']=$d_method;

                    }

                    $data['source_type']=$goods['source_type'];
                    $data['store_id']=$goods['store_id'];
                    $data['create_time']=time();
                    $data['update_time']=time();
                    $cart_id = Db::name("cart")
                        ->insertGetId($data);
                    if($cart_id<=0){
                        throw new Exception("更新失败");
                    }
                    Db::commit();
                    return  $cart_id;

                }catch (Exception $e){
                    Db::rollback();
                    returnJson(-2004,'新增购物车失败');
                }
            }
        }


    }

    /**
     * 购物车列表
     */
    public function getCartList($data,$page_num,$current_page)
    {

        $member_id=$data['member_id'];
        if(in_array($data['source_type'],[2,3])){//供应链商品
            $where=['c.member_id'=>$member_id];
            $where['c.source_type']=$data['source_type'];
            $where['g.status']=1;

            $cartList=Db::name("cart")->alias("c")
                ->join("mm_choice_goods g","c.goods_id=g.goods_id ")
                ->field("c.cart_id,c.store_id,c.goods_id,c.spec_id,c.goods_id,c.member_id,c.goods_num,c.spec_name,c.rebate_score,
                c.rebate_coin,g.title g_name,g.market_price cost_price,c.score_amount price,c.coin_amount coin_price,g.cover cover_pic,g.source")
                ->where($where)
                ->select();

            return  $cartList;
        }else{
            $where=['c.member_id'=>$member_id];
            $where['g.is_delete']=1;
            $where['g.source_type']=$data['source_type'];
            $where['g.status']=1;
            $cartList=Db::name("cart")->alias("c")
                ->join("mm_goods g","c.goods_id=g.goods_id ")
                ->join("mm_goods_info gn","c.goods_id=gn.goods_id")
                ->join("mm_goods_spec gs","c.spec_id=gs.gs_id")

                ->field("c.cart_id,c.store_id,c.goods_id,c.spec_id,c.goods_id,c.member_id,c.goods_num,c.d_method,c.d_type,c.d_fee,g.source_type,g.g_type,g.g_name,g.limit_number,g.cover_pic,
            g.limit_start_time,g.limit_end_time,g.limit_num_status,g.limit_time_status,gs.num,gs.name spec_name,gs.price,gs.cost_price,gs.coin_price,gs.gold_coin_num,gs.proportion,gn.distribution_method,gn.delivery_fee")
                ->where($where)
                //  ->page($current_page,$page_num)
                ->select();

            //获取分销比例
            $setInfo = Db::name("system_config")->where(['field_name' => "points_award_config"])
                ->value("field_value");
            $points_award_config = json_decode($setInfo, true);
            $buyer = $points_award_config['buyer'];
            if($cartList){

                $tm=time();
                //获取商家列表
                $storeIds=array_unique(array_column($cartList,"store_id"));


                $storeArr=Db::name("store_apply")->alias("a")
                    ->join("mm_store_detail s","s.sa_id=a.sa_id")
                    ->where("a.sa_id","in",$storeIds)
                    ->column("a.sa_id,a.company_name,s.distribution_method,s.delivery_type","a.sa_id");

                $cartDataList=[];
                $carts=[];
                foreach ($cartList as &$cart){

                    //判断活动是否限时有效
                    if($cart['limit_time_status']==2&&($tm<$cart['limit_start_time']||$tm>$cart['limit_end_time'])){//限时

                        continue;
                    }
                    //判断商品是否限购
                    if($cart['limit_num_status']==2){//限购

                        $buyNums=Db::name("order_goods")->alias("og")
                            ->join("mm_order o","og.order_id=o.order_id")
                            ->where(['o.pay_status'=>2,"og.goods_id"=>$cart["goods_id"],"o.member_id"=>$cart["member_id"]])
                            ->value("og.goods_num");
                        if($buyNums>=$cart['limit_number']){

                            continue;
                        }
                    }
                    if($cart['d_method']>0){
                        //判断当前店铺是否更改配送方式及运费
                        $distribution_method=explode(",",$storeArr[$cart['store_id']]['distribution_method']);
                        #店铺应该没有选择消费方式到店消费,后续需要判断设置,此, 下面代码不能这么用,先注释
//                        if(!in_array($cart['d_method'],$distribution_method)){
//
//                            continue;
//                        }
                        if($cart['d_method']==1&&$cart['d_type']==1&&$cart['d_fee']!=$cart['delivery_fee']){//送货上门商家自己配送 运费匹配

                            continue;
                        }
                    }

                    unset($cart['limit_num_status']);
                    unset($cart['limit_number']);
                    if($cart['goods_num']>$cart['num']&&!in_array($cart['g_type'],[4,5])){

                        continue;
                    }
                    //组合显示列表
                    $storeID=$cart['store_id'];
//                if(empty($total_score[$storeID])){
//                    $total_score[$storeID]=0;
//                }
//                if(empty( $total_coin[$storeID])){
//                    $total_coin[$storeID]=0;
//                }
//                if(empty($total_shipping_fee[$storeID])){
//                    $total_shipping_fee[$storeID]=0;
//                }
//                if(empty($total_goods_num[$storeID])){
//                    $total_goods_num[$storeID]=0;
//                }

                    if($cart['source_type']==1){
                        $companyName="联盟商家-".$storeArr[$cart['store_id']]['company_name'];
                    }elseif($cart['source_type']==2){
                        $companyName="返利商城";
                    }elseif($cart['source_type']==3){
                        $companyName="爆品商城";
                    }elseif($cart['source_type']==4){
                        $companyName="干货分享";
                    }
                    if($cart['proportion']>0){//计算返积分
                        $cart['rebate_score'] = $cart['price']*$cart['proportion']/100 * $buyer / 100;
                    }else{
                        $cart['rebate_score']=0;
                    }
                    unset($cart['num']);
                    unset($cart['proportion']);
                    unset($cart['source_type']);
                    $cart['is_select']=0;

                    $carts[$storeID][]=$cart;
//                $total_goods_num[$storeID]+=$cart['goods_num'];
//                $total_score[$storeID]+=$cart['price'];
//                $total_coin[$storeID]+=$cart['coin_price'];
//                $total_shipping_fee[$storeID]+=$cart['delivery_fee'];
                    $cartDataList[$storeID]=["company_name"=>$companyName,'store_id'=>$storeID,'cart_list'=>$carts[$storeID],'total_score'=>0,'total_shipping_fee'=>0,'total_goods_num'=>0,'total_coin'=>0];

                }
            }else{
                $cartDataList=[];
            }
            $cartShowList=[];
            if(!empty($cartDataList)){
                foreach($cartDataList as $cart){
                    $cartShowList[]=$cart;
                }
            }

            return $cartShowList;
        }

    }

    /**
     * 更新购物车配送
     */
    public function updateDelivery($param,$member_id){
        $cart_list=$param['cart_list'];
        $cart_list=explode(",",$cart_list);
        $d_mothod=$param['d_mothod'];
        if(!in_array($d_mothod,array(1,2))){
            returnJson(-2003,'参数错误');
        }
        //获取商品信息
        $storeInfo=Db::name("cart")->alias("c")->join("mm_store_detail s","s.sa_id=c.store_id")->where(["c.cart_id"=>$param['cart_id']])->field("c.store_id,s.distribution_method,s.delivery_type,s.delivery_fee")->find();
        $distribution_method=explode(",",$storeInfo['distribution_method']);
        if(!in_array($d_mothod,$distribution_method)){
            returnJson(-2003,'当前店铺该配送方式已不存在');
        }
        $store_id=$storeInfo['store_id'];
        if($d_mothod==1){
            if($storeInfo['delivery_type']==1){//商家自送
                $updData=["d_method"=>$d_mothod,"d_type"=>1,"d_fee"=>$storeInfo['delivery_fee']];
            }else if($storeInfo['delivery_type']==1) {//第三方配送
                //计算第三方配送运费金额
                $updData=["d_method"=>$d_mothod,"d_type"=>2];
            }

        }elseif($d_mothod==2){//到店消费
            $updData=["d_method"=>$d_mothod,"d_type"=>0,"d_fee"=>0.00];

        }
        $nums=Db::name('cart') ->where(['member_id'=>$member_id,"cart_id"=>$param['cart_id']])->update($updData);

        if($nums>0){
            $cartList=Db::name('cart')->alias("c") ->join("mm_goods_spec gs","c.spec_id=gs.gs_id")->where(['c.member_id'=>$member_id,"c.cart_id"=>['in',$cart_list],'c.store_id'=>$store_id])->field("gs.price,gs.coin_price,c.d_fee")->select();
            $total_score=0;
            $total_shipping_fee=0;
            $total_coin=0;
            foreach ($cartList as $item){
                $total_score+=$item['price']*$item['goods_num'];
                $total_shipping_fee+=$item['d_fee'];
                $total_coin+=$item['coin_price']*$item['goods_num'];
            }
            returnJson(200,'success',['total_score'=>$total_score,'total_shipping_fee'=>$total_shipping_fee,'total_coin'=>$total_coin]);

        }else{
            returnJson(-2004,'购物车商品更新失败');
        }

    }

    public function updateNums($param,$member_id){
        if($param['goods_num']<=0){
            returnJson(-2003,'参数错误');
        }
        $cart_list=$param['cart_list'];
        $cart_list=explode(",",$cart_list);
        //判断当前规格库存是否足够
        //获取规定ID
        $specInfo=Db::name('cart') ->where(['member_id'=>$member_id,"cart_id"=>$param['cart_id']])->field("goods_id,spec_id,store_id")->find();
        $spec_id=$specInfo['spec_id'];
        $store_id=$specInfo['store_id'];
        $goods_id=$specInfo['goods_id'];
        //获取商品类型
        $gType=Db::name('goods') ->where(["goods_id"=>$goods_id])->value("g_type");
        //获取当前规格库存
        $spec_num=Db::name('goods_spec') ->where(["gs_id"=>$spec_id])->value("num");
        if($spec_num<$param['goods_num']&&!in_array($gType,[4,5])){
            returnJson(-2004,'库存不足');
        }


        $nums=Db::name('cart') ->where(['member_id'=>$member_id,"cart_id"=>$param['cart_id']])->update(["goods_num"=>$param['goods_num']]);


        if($nums>0){

            $cartList=Db::name('cart')->alias("c") ->join("mm_goods_spec gs","c.spec_id=gs.gs_id")->where(['c.member_id'=>$member_id,"c.cart_id"=>['in',$cart_list],'c.store_id'=>$store_id])->field("gs.price,gs.coin_price,c.d_fee")->select();

            $total_score=0;
            $total_shipping_fee=0;
            $total_coin=0;
            foreach ($cartList as $item){
                $total_score+=$item['price']*$item['goods_num'];
                $total_shipping_fee+=$item['d_fee'];
                $total_coin+=$item['coin_price']*$item['goods_num'];
            }
            returnJson(200,'success',['total_score'=>$total_score,'total_shipping_fee'=>$total_shipping_fee,'total_coin'=>$total_coin]);
        }else{
            returnJson(-2004,'购物车商品更新失败');
        }

    }

    public function cartSelected($param,$member_id){
        $store_id=$param['store_id'];
        $cart_list=$param['cart_list'];
        $cart_list=explode(",",$cart_list);
        $cartList=Db::name('cart')->alias("c") ->join("mm_goods_spec gs","c.spec_id=gs.gs_id")->where(['c.member_id'=>$member_id,"c.cart_id"=>['in',$cart_list],'c.store_id'=>$store_id])->field("gs.price,gs.coin_price,c.d_fee")->select();

        $total_score=0;
        $total_shipping_fee=0;
        $total_coin=0;
        foreach ($cartList as $item){
            $total_score+=$item['price']*$item['goods_num'];
            $total_shipping_fee+=$item['d_fee'];
            $total_coin+=$item['coin_price']*$item['goods_num'];
        }
        returnJson(200,'success',['total_score'=>$total_score,'total_shipping_fee'=>$total_shipping_fee,'total_coin'=>$total_coin]);
    }


    /**
     * 删除购物车中商品
     */
    public function removeCart($param,$member_id)
    {
        $store_id=Db::name('cart')
            ->where(['member_id'=>$member_id,"goods_id"=>$param['goods_id'],"spec_id"=>$param['spec_id']])
            ->value("store_id");
        $cart_list=$param['cart_list'];
        $nums=Db::name('cart')
            ->where(['member_id'=>$member_id,"goods_id"=>$param['goods_id'],"spec_id"=>$param['spec_id']])
            ->delete();
        if($nums>0){
            $cartList=Db::name('cart')->alias("c")
                ->join("mm_goods_spec gs","c.spec_id=gs.gs_id")
                ->where(['c.member_id'=>$member_id,"c.cart_id"=>['in',$cart_list],'c.store_id'=>$store_id])
                ->field("gs.price,gs.coin_price,c.d_fee")->select();
            $total_score=0;
            $total_shipping_fee=0;
            $total_coin=0;
            foreach ($cartList as $item){
                $total_score+=$item['price']*$item['goods_num'];
                $total_shipping_fee+=$item['d_fee'];
                $total_coin+=$item['coin_price']*$item['goods_num'];
            }
            returnJson(200,'success',['total_score'=>$total_score,'total_shipping_fee'=>$total_shipping_fee,'total_coin'=>$total_coin]);
        }else{
            returnJson(-2004,'购物车商品移除失败');
        }

    }

    /**
     * 供应链订单计算价格
     */

    public function computePrice($goods_id,$source_type,$agreement_price){


        if($source_type==2){//返利商城
            $getReturnPop=getReturnPop($goods_id,1);
            $price= sprintf("%.1f",$agreement_price * $getReturnPop / 100);
            $gold_coin_num=0;
            $gold_coin=0;
            $direct_push=$agreement_price / 100* 0.05 ;
            $inter_push=$agreement_price / 100* 0.05 ;
            $activity_buyer=$agreement_price / 100* 0.2;
            $activity_plateform=$agreement_price/ 100* 0.2;
            $activity_invest=0;
            $activity_company=0;
        }elseif($source_type==3){//爆品商城
            $getReturnPop=getReturnPop($goods_id,2);
            $price = sprintf("%.1f",$agreement_price * $getReturnPop / 100);
            $gold_coin = sprintf("%.1f",$agreement_price * $getReturnPop * 2 / 100);
            $gold_coin_num=0;
            $direct_push=0;//直推
            $inter_push=0;//间推
            $activity_buyer=0;//买家
            $activity_plateform=0;//平台
            $activity_invest=0;//招商
            $activity_company=0;//子公司
        }
        return ['price'=>$price,'gold_coin'=>$gold_coin,'direct_push'=>$direct_push,
            'inter_push'=>$inter_push,'activity_buyer'=>$activity_buyer,'activity_plateform'=>$activity_plateform,
            'activity_invest'=>$activity_invest,'activity_company'=>$activity_company,'gold_coin_num'=>$gold_coin_num];

    }

    /**
     * 批量删除购物车数据
     */
    public function cartDelAll($cart_ids,$member_id){
       /* dump($cart_ids);
        $where['cart_id']=['in',$cart_ids];
        dump($where);
        $data=Db::name('cart')->where($where)
            ->select();*/
        Db::name('cart')
            ->where(['cart_id'=>['in',$cart_ids],'member_id'=>$member_id])
            ->delete();

        return true;
    }


}